const bcrypt = require('bcrypt');
const { pool } = require('../config/db');

// 创建管理员用户表
exports.createAdminUserTable = async () => {
  const query = `
    CREATE TABLE IF NOT EXISTS admin_users (
      id INT AUTO_INCREMENT PRIMARY KEY,
      username VARCHAR(50) NOT NULL UNIQUE,
      password VARCHAR(255) NOT NULL,
      nickname VARCHAR(50),
      role VARCHAR(20) DEFAULT 'admin',
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )
  `;
  
  try {
    await pool.execute(query);
    console.log('Admin user table created successfully!');
    
    // 检查是否存在默认管理员账户，如果不存在则创建
    const [existingAdmin] = await pool.execute('SELECT id FROM admin_users WHERE username = ?', ['admin']);
    
    if (existingAdmin.length === 0) {
      // 创建默认管理员账户
      const hashedPassword = await bcrypt.hash('admin123', 10);
      await pool.execute(
        'INSERT INTO admin_users (username, password, nickname, role) VALUES (?, ?, ?, ?)',
        ['admin', hashedPassword, '超级管理员', 'superadmin']
      );
      console.log('Default admin account created with username: admin, password: admin123');
    }
  } catch (error) {
    console.error('Error creating admin user table:', error);
  }
};

// 验证管理员用户登录
exports.verifyAdminLogin = async (username, password) => {
  try {
    const query = 'SELECT * FROM admin_users WHERE username = ?';
    const [rows] = await pool.execute(query, [username]);
    
    if (rows.length === 0) {
      return { success: false, message: '用户名不存在' };
    }
    
    const user = rows[0];
    const isPasswordMatch = await bcrypt.compare(password, user.password);
    
    if (!isPasswordMatch) {
      return { success: false, message: '密码错误' };
    }
    
    // 不返回密码
    const { password: _, ...userInfo } = user;
    return { success: true, user: userInfo };
  } catch (error) {
    console.error('验证管理员登录失败:', error);
    return { success: false, message: '服务器错误' };
  }
};